#include <iostream>
#include "Thread.hpp"
#include <vector>


using namespace ThreadModule;

#define NUM 4

int ticketnum = 10000;//临界资源

class ThreadData
{
public:
    std::string name;
    pthread_mutex_t* lock_ptr;
};

void Ticket(ThreadData& td)
{
    while(true)
    {
        pthread_mutex_lock(td.lock_ptr);//加锁
        if(ticketnum > 0)
        {
            usleep(1000);
            //1.抢票
            printf("get a new ticket, who get it: %s, id: %d\n",td.name.c_str(),ticketnum--);
            pthread_mutex_unlock(td.lock_ptr);//解锁
            //入库模拟操作
            usleep(50);       
        }
        else
        {
            pthread_mutex_unlock(td.lock_ptr);
            break;
        }
    }
}

int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock,nullptr);

    //1.构建线程对象
    std::vector<Thread<ThreadData>> threads;
    for(int i = 0;i < NUM;i++)
    {
        ThreadData* td = new ThreadData();
        td->lock_ptr = &lock;
        threads.emplace_back(Ticket,*td);
        td->name = threads.back().Name();
    }

    //2.启动线程
    for(auto& thread:threads)
    {
        thread.Start();
    }

    //3.等待线程
    for(auto& thread:threads)
    {
        thread.Join();
    }

    pthread_mutex_destroy(&lock);
    return 0;
}

